<template>
  <div class="xw-wrap login">
    <h2>登 录</h2>
    <button @click="toPathFun({ path: '/' })">去首页</button>
    <button @click="emitThrottle('xw')">节流</button>
    <button @click="emitDebounce('xw')">防抖</button>
    <button @click="loginFun">Login</button>
  </div>
</template>

<script setup lang="ts">
import { debounce, throttle } from '@/utils'
import { useRouter } from 'vue-router'
import { login, getUser } from '@/api/user'
import { useUserStore } from '@/store/useStore'

console.log('login')
const router = useRouter()
const toPathFun = ({ path, name }: { path?: string; name?: string }) => {
  path && router.push({ path: path, query: { name: 'xiaowu' } })
  name && router.push({ name: name, query: { name: 'xiaowu', id: 1 } })
}
const userStore = useUserStore()
let n = 0
const testEmit = (name) => {
  n++
  console.log('emit==', name, n)
}
const emitThrottle = throttle(testEmit)
const emitDebounce = debounce(testEmit)

console.log('query', router.currentRoute.value.query)
console.log('params', router.currentRoute.value.params)
console.log('search', location.search)
const loginFun = () => {
  login({ username: 'xw', password: '123' }).then((res) => {
    console.log('res', res)
    const { accessToken, refreshToken, userId } = res.data
    userStore.accessToken = accessToken
    userStore.refreshToken = refreshToken

    const redirect = router.currentRoute.value.query?.redirect as string
    router.push({ path: redirect || '/' })
    getUserFun({ userId })
  })
}
const getUserFun = ({ userId }) => {
  getUser({ userId }).then((res) => {
    const { username } = res
    userStore.name = username
  })
}
</script>

<style lang="scss" scoped></style>
